<template>
  <div class="class-management">
    <div class="page-header">
      <h2>班级管理</h2>
      <el-button type="primary" @click="handleAddClass">
        <el-icon><plus /></el-icon>
        添加班级
      </el-button>
    </div>
    
    <!-- 搜索 -->
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索班级名称、班主任"
        prefix-icon="Search"
        style="width: 300px;"
        @keyup.enter="handleSearch"
      >
      </el-input>
      
      <el-button @click="handleSearch" style="margin-left: 16px;">搜索</el-button>
      <el-button @click="handleReset" style="margin-left: 8px;">重置</el-button>
    </div>
    
    <!-- 班级表格 -->
    <el-card class="table-card" style="margin-top: 16px;">
      <el-table
        v-loading="loading"
        :data="classesData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="班级编号" width="120" sortable></el-table-column>
        <el-table-column prop="name" label="班级名称" width="200" sortable></el-table-column>
        <el-table-column prop="headTeacher" label="班主任" width="150"></el-table-column>
        <el-table-column prop="studentCount" label="学生人数" width="100" sortable></el-table-column>
        <el-table-column prop="major" label="专业" width="150"></el-table-column>
        <el-table-column prop="grade" label="年级" width="100" sortable></el-table-column>
        <el-table-column prop="creationDate" label="创建日期" width="150" sortable>
          <template #default="scope">
            <span>{{ formatDate(scope.row.creationDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="班级描述"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEditClass(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDeleteClass(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 分页 -->
    <div class="pagination" style="margin-top: 16px;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑班级对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="classFormRef"
        :model="classForm"
        :rules="classRules"
        label-width="100px"
      >
        <el-form-item label="班级编号" prop="id">
          <el-input v-model="classForm.id" :disabled="isEditMode"></el-input>
        </el-form-item>
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="classForm.name"></el-input>
        </el-form-item>
        <el-form-item label="班主任" prop="headTeacher">
          <el-input v-model="classForm.headTeacher"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="classForm.major"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model.number="classForm.grade" type="number"></el-input>
        </el-form-item>
        <el-form-item label="创建日期" prop="creationDate">
          <el-date-picker
            v-model="classForm.creationDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="班级描述" prop="description">
          <el-input v-model="classForm.description" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveClass">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 搜索条件
const searchQuery = ref('')

// 表格数据
const classesData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedClasses = ref([])

// 对话框相关
const dialogVisible = ref(false)
const isEditMode = ref(false)
const dialogTitle = computed(() => isEditMode.value ? '编辑班级' : '添加班级')
const classFormRef = ref(null)
const classForm = reactive({
  id: '',
  name: '',
  headTeacher: '',
  studentCount: 0,
  major: '',
  grade: '',
  creationDate: '',
  description: ''
})

// 表单验证规则
const classRules = {
  id: [
    { required: true, message: '请输入班级编号', trigger: 'blur' },
    { pattern: /^\d+$/, message: '班级编号必须为数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 50, message: '班级名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  headTeacher: [
    { required: true, message: '请输入班主任姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请输入年级', trigger: 'blur' },
    { type: 'number', min: 1, max: 6, message: '年级在 1 到 6 之间', trigger: 'blur' }
  ],
  creationDate: [
    { required: true, message: '请选择创建日期', trigger: 'change' }
  ]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 加载班级数据
const loadClasses = async () => {
  loading.value = true
  try {
    // 真实的API调用
    const response = await axios.get('/api/classes', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value
      }
    })
    classesData.value = response.data.data
    total.value = response.data.total
  } catch (error) {
    console.error('加载班级数据失败:', error)
    ElMessage.error('加载班级数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadClasses()
}

// 处理重置
const handleReset = () => {
  searchQuery.value = ''
  currentPage.value = 1
  loadClasses()
}

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  loadClasses()
}

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadClasses()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedClasses.value = selection
}

// 打开添加班级对话框
const handleAddClass = () => {
  isEditMode.value = false
  // 重置表单
  Object.keys(classForm).forEach(key => {
    classForm[key] = key === 'studentCount' ? 0 : ''
  })
  dialogVisible.value = true
}

// 打开编辑班级对话框
const handleEditClass = (row) => {
  isEditMode.value = true
  // 填充表单
  Object.assign(classForm, row)
  dialogVisible.value = true
}

// 保存班级
const handleSaveClass = async () => {
  try {
    await classFormRef.value.validate()
    
    // 真实的API调用
    if (isEditMode.value) {
      await axios.put(`/api/classes/${classForm.id}`, classForm)
      ElMessage.success('班级信息更新成功')
    } else {
      await axios.post('/api/classes', classForm)
      ElMessage.success('班级添加成功')
    }
    
    dialogVisible.value = false
    loadClasses()
  } catch (error) {
    console.error('保存班级数据失败:', error)
    ElMessage.error('保存班级数据失败，请稍后重试')
  }
}

// 删除班级
const handleDeleteClass = (id) => {
  ElMessageBox.confirm(
    '确定要删除这个班级吗？删除后将无法恢复。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // 真实的API调用
      await axios.delete(`/api/classes/${id}`)
      ElMessage.success('班级删除成功')
      loadClasses()
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 关闭对话框
const handleDialogClose = () => {
  if (classFormRef.value) {
    classFormRef.value.resetFields()
  }
}

// 初始加载数据
loadClasses()
</script>

<style scoped>
.class-management {
  height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.search-section {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .search-section .el-input {
    width: 100% !important;
  }
  
  .search-section .el-button {
    margin-left: 0 !important;
  }
  
  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
}
</style>